// index.js
const implAddress = getApp().globalData.implAddress;
Page({
  data: {
    msg: 'hello world',
    posterUrl: [],
    //可展示的商品数据
    goods: [{
      item_id: 1,
      item_img: '../../images/tabbar/indexSelected.png',
      item_name: '第一个示例',
      item_detail: '简介简介简介简介简介简介简介',
      item_account: 100,
      item_total:1
    }, ],
    //所有商品数据
    allGoods: [],
    //搜索字段
    searchInput: ''
  },
  onLoad() {
    const that = this
    //获取所有商品列表
    wx.request({
      url: implAddress + 'item/all',
      method: 'GET',
      success: function (res) {
        console.log('主页商品信息', res.data.data)
        that.setData({
          goods: res.data.data,
          allGoods: res.data.data
        })
      },
      fail: function (err) {
        console.error(err)
      },
    })
    //获取海报列表
    wx.request({
      url: implAddress + 'poster/all',
      method: 'GET',
      success: function (res) {
        console.log('主页海报信息', res.data.data)
        that.setData({
          posterUrl: res.data.data
        })
      },
      fail: function (err) {
        console.error(err)
      },
    })
  },
  navTo: function (event) {
    var goodId = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/singleGood/singleGood?goodId=' + goodId,
      fail: function () {
        wx.showToast({
          title: '跳转失败！',
          icon: 'error'
        })
      }
    })
  },
  search: function (e) {
    const that = this;
    const preSearchWord = e.detail.value
    setTimeout(function () {
      //开始搜索
      let goodArray = that.data.allGoods
      let result = goodArray.find(goodArray => goodArray.item_name === preSearchWord)
      //输出搜索结果
      let resultArray = []
      if (result) {
        console.log('搜索成功！')
        resultArray.push(result)
        that.setData({
          goods: resultArray
        })
      } else {
        console.log('没有匹配的商品')
        //还原显示列表
        that.setData({
          goods:that.data.allGoods
        })
      }
    }, 2000)
  }
})